# -*- coding: utf-8 -*-
import time
import hmac
import hashlib
import base64
import requests


def get_seconds():
    return lambda: int(round(time.time() * 1000))


def sign(params, api, version, ak, sk):
    headers = dict()
    headers['_api_name'] = api
    headers['_api_version'] = version
    headers['_api_access_key'] = ak
    headers['_api_timestamp'] = get_seconds()()
    params = dict(params, **headers)
    keys = params.keys()
    keys.sort()
    sign_params = []
    for key in keys:
        if key and key not in "_api_signature":
            sign_params.append("{}={}".format(key, params[key]))
    sign_params_str = '&'.join(sign_params)
    signature = base64.standard_b64encode(hmac.new(sk, sign_params_str, hashlib.sha1).digest())
    params["_api_signature"] = signature
    return {"X-AOSP-ACCESS-KEY": ak, "X-AOSP-SIGNATURE": signature}, params


def do_text_get(url, api, version, ak, sk, params={}):
    headers,data = sign(params, api, version, ak, sk)
    return requests.get(url, headers=headers).text


def do_json_get(url, api, version, ak, sk, params={}):
    headers,data = sign(params, api, version, ak, sk)
    headers["Content-Type"] = "application/json"
    return requests.get(url, headers=headers).json()


def do_text_post(url, api, version, ak, sk, data={}):
    headers,data = sign(data, api, version, ak, sk)
    return requests.post(url, data=data, headers=headers).text


def do_json_post(url, api, version, ak, sk, data={}):
    headers,data = sign(data, api, version, ak, sk)
    headers["Content-Type"] = "application/json"
    return requests.post(url, data=data, headers=headers).json


